new Vue({
  el: '#app',
  data() {
    return {
      detail: null,
      stagedPayments: [],
      pageAcq: null,
      // 入口来源：仅当从采购订单入口进入时可操作通过/拒绝
      fromPurchaseDetail: false,
    };
  },
  mounted() {
    // 识别入口来源
    try {
      const fromPage = getQueryObject(window.location.href, 'fromPage') || '';
      this.fromPurchaseDetail = String(fromPage) === 'purchase_order';
    } catch (e) { this.fromPurchaseDetail = false; }
    this.fetchDetail();
  },
  methods: {
    handleBack() {
      try {
        const fromPage = getQueryObject(window.location.href, 'fromPage') || '';
        const applyId = getQueryObject(window.location.href, 'applyId') || '';
        if (fromPage === 'purchase_order') {
          window.location.href = '../purchase_order/index.html';
          return;
        }
        if (fromPage === 'acquisition_order') {
          window.location.href = './index.html';
          return;
        }
        const acqId = this.detail && this.detail.Acquisition_Unit_Price_SerialNumber;
        if (acqId) {
          window.location.href = `../acquisition_hall/list.html?acqId=${encodeURIComponent(acqId)}`;
        } else {
          window.location.href = './index.html';
        }
      } catch (e) {
        window.location.href = './index.html';
      }
    },
    // 仅当从采购订单入口且订单为待审核（Row_Status='0'）时允许操作
    canOperate(row) {
      return !!this.fromPurchaseDetail && String((row && row.Row_Status) || '') === '0';
    },
    formatStatus(status) {
      switch (String(status)) {
        case '0': return '待审核';
        case '2': return '通过';
        case '3': return '拒绝';
        default: return '未知';
      }
    },
    statusTagType(status) {
      switch (String(status)) {
        case '0': return 'warning';
        case '2': return 'success';
        case '3': return 'danger';
        default: return 'info';
      }
    },
    formatAddress(s) {
      if (!s) return '';
      const p = s.ProvinceNumber || '';
      const c = s.CityNumber || '';
      const d = s.CountyNumber || '';
      const a = s.Detailed_Address || '';
      return `${p}${c}${d}${a}`;
    },
    formatAcqAddress(s) {
      if (!s) return '';
      const p = s.ProvinceNumber || '';
      const c = s.CityNumber || '';
      const d = s.CountyNumber || '';
      const a = s.Detailed_Address || '';
      return `${p}${c}${d}${a}`;
    },
    async fetchDetail() {
      try {
        const applyId = getQueryObject(window.location.href, 'applyId') || '';
        if (!applyId) return;
        const res = await httpRequest({
          url: '/generalBusiness/generalQueryByTableName',
          data: { Data: 'acquisition_order', Condition: `Acquisition_Order_SerialNumber='${applyId}'` },
          type: 'GET'
        });
        const arr = Array.isArray(res) ? res : (res.Data || []);
        this.detail = arr && arr[0] ? arr[0] : null;

        // 查询分阶段付款方案：优先订单的 paystages，其次报价的 staged_payment；并查询求购单原信息
        if (this.detail) {
          const id = this.detail.Acquisition_Order_SerialNumber;
          const unitId = this.detail.Acquisition_Unit_Price_SerialNumber;
          // 顶部：查询并挂载求购单原信息
          try {
            if (unitId) {
              const upRes = await httpRequest({
                url: '/generalBusiness/generalQueryByTableName',
                data: { Data: 'acquisition_unitprice', Condition: `Acquisition_Unit_Price_SerialNumber='${unitId}'` },
                type: 'GET'
              });
              const upArr = Array.isArray(upRes) ? upRes : (upRes.Data || []);
              this.pageAcq = upArr && upArr[0] ? upArr[0] : null;
            } else { this.pageAcq = null; }
          } catch (e) { this.pageAcq = null; }
          try {
            // 直接按报价编号查询并展示阶段模板，不做排序
            if (unitId) {
              const spRes = await httpRequest({
                url: '/generalBusiness/generalQueryByTableName',
                data: { Data: 'acquisition_unitprice_staged_payment', Condition: `Acquisition_Unit_Price_SerialNumber='${unitId}'` },
                type: 'GET'
              });
              this.stagedPayments = Array.isArray(spRes) ? spRes : (spRes.Data || []);
            } else {
              this.stagedPayments = [];
            }
          } catch (e) {
            this.stagedPayments = [];
          }

          // 查询并挂载拒绝记录
          try {
            const hasList = Array.isArray(this.list) && this.list.length > 0;
            if (hasList) {
              const ids = (this.list || []).map(i => i.Acquisition_Order_SerialNumber).filter(Boolean);
              if (ids.length > 0) {
                const logs = await httpRequest({
                  url: '/generalBusiness/generalQueryByTableName',
                  data: {
                    Data: 'acquisition_order_examine_log',
                    Condition: `Acquisition_Order_SerialNumber IN (${ids.map(v => `'${v}'`).join(',')})`
                  },
                  type: 'GET'
                });
                const arr = Array.isArray(logs) ? logs : (logs.Data || []);
                const map = {};
                arr.forEach(l => {
                  const k = l.Acquisition_Order_SerialNumber;
                  if (!map[k]) map[k] = [];
                  map[k].push(l);
                });
                this.list = this.list.map(row => ({
                  ...row,
                  examineLogs: map[row.Acquisition_Order_SerialNumber] || []
                }));
              }
            } else {
              const logsRes = await httpRequest({
                url: '/generalBusiness/generalQueryByTableName',
                data: { Data: 'acquisition_order_examine_log', Condition: `Acquisition_Order_SerialNumber='${id}'` },
                type: 'GET'
              });
              const logsArr = Array.isArray(logsRes) ? logsRes : (logsRes.Data || []);
              this.$set(this.detail, 'examineLogs', logsArr || []);
            }
          } catch (e) {
            if (Array.isArray(this.list) && this.list.length > 0) {
              // 列表模式下查询失败不影响其他展示
            } else {
              this.$set(this.detail, 'examineLogs', []);
            }
          }
        }
      } catch (e) {
        console.error(e);
        this.$message.error('加载详情失败，请稍后重试');
      }
    },
    // 通过订单
    acceptOrder(row) {
      try {
        const tableName = 'acquisition_order';
        const primaryKey = 'Acquisition_Order_SerialNumber';
        const id = row && row[primaryKey];
        if (!id) { this.$message.error('未获取到订单编号'); return; }
        if (!this.fromPurchaseDetail) { this.$message.error('仅从采购订单入口可操作'); return; }

        httpRequest({
          url: '/generalBusiness/generalQueryByTableNameWithOriginal',
          data: { Data: tableName, Condition: `${primaryKey}='${id}'` },
          type: 'POST'
        }).then(async data => {
          if (!Array.isArray(data) || data.length !== 1) { this.$message.error('订单不存在或存在重复记录'); return; }
          data[0].Row_Status = '2';
          // 初始化未付款、未收款与订单金额一致
          const amtStr = String((data[0].Amount !== undefined && data[0].Amount !== null) ? data[0].Amount : (row.Amount || ''));
          data[0].Remain_Amount = amtStr;
          data[0].Unamount = amtStr;

          // 初始化未发货、未收货与交易数量一致
          const qtyStr = String((data[0].Quantity !== undefined && data[0].Quantity !== null) ? data[0].Quantity : (row.Quantity || ''));
          data[0].Undelivery_Quantity = qtyStr;
          data[0].Unreceipt_Quantity = qtyStr;

          const orderAmount = Number((data[0] && data[0].Amount) || row.Amount || 0);
          const unitPriceId = row.Acquisition_Unit_Price_SerialNumber || data[0].Acquisition_Unit_Price_SerialNumber || '';

          // 初始化阶段付款方案（若不存在）
          let paystagesToAdd = [];
          try {
            const existed = await httpRequest({
              url: '/generalBusiness/generalQueryByTableNameWithOriginal',
              data: { Data: 'acquisition_order_paystages', Condition: `Acquisition_Order_SerialNumber='${id}'` },
              type: 'POST'
            });
            const hasExisting = Array.isArray(existed) ? existed.length > 0 : ((existed && existed.Data) ? existed.Data.length > 0 : false);
            if (!hasExisting && unitPriceId) {
              const stagedRes = await httpRequest({
                url: '/generalBusiness/generalQueryByTableNameWithOriginal',
                data: { Data: 'acquisition_unitprice_staged_payment', Condition: `Acquisition_Unit_Price_SerialNumber='${unitPriceId}'` },
                type: 'POST'
              });
              const stagedArr = Array.isArray(stagedRes) ? stagedRes : (stagedRes && stagedRes.Data) || [];
              paystagesToAdd = (stagedArr || []).map(sp => {
                const percentVal = Number(sp.Percent || 0);
                const due = Number.isFinite(orderAmount * percentVal / 100)
                  ? Number((orderAmount * percentVal / 100).toFixed(2))
                  : '';
                return {
                  Acquisition_Order_Paystages_SerialNumber: '',
                  Acquisition_Order_SerialNumber: id,
                  Acquisition_Unit_Price_Staged_Payment_SerialNumber: sp.Acquisition_Unit_Price_Staged_Payment_SerialNumber || '',
                  Stage_Name: sp.Stage_Name || '',
                  Percent: sp.Percent !== undefined ? sp.Percent : '',
                  Due_Amount: due !== '' ? String(due) : '',
                  Trading_Amount: due !== '' ? String(due) : '',
                  Remain_Amount: due !== '' ? String(due) : '',
                  Paid_Amount: '0',
                  Collection_Amount: '0',
                  Unamount: due !== '' ? String(due) : '0',
                  Collection_Date: '',
                  Row_Status: '0'
                };
              });
            }
          } catch (e) { /* 初始化失败不阻塞接受逻辑 */ }

          const lJSONObject_Modify = {}; lJSONObject_Modify[tableName] = data;
          const lJSONObject_DataSet = { Modify: lJSONObject_Modify, Add: {} };
          if (paystagesToAdd.length > 0) lJSONObject_DataSet.Add['acquisition_order_paystages'] = paystagesToAdd;
          const Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
          lJSONObject_DataSet['Add']['base_operation_log'] = [{
            Operation_Type: '0', Operation_Path: getRelativePath(), Operation_Description: '接受采购订单',
            Operation_Main, Operation_Interface: 'generalSaveByRequestBody', Operation_IP: getIpAddress()
          }];
          return httpRequest({ contentType: 'JSON', url: '/generalBusiness/generalSaveByRequestBody', data: JSON.stringify({ Data: lJSONObject_DataSet }) });
        }).then(res => {
          if (res && (res.Status === 'success')) {
            this.$message.success('已通过');
            this.$set(row, 'Row_Status', '2');
            // 成功后返回来源页
            this.handleBack();
          }
          else if (res) { this.$message.error(res.Message || '保存失败'); }
        }).catch(() => this.$message.error('系统错误，请联系开发者!'));
      } catch (e) { console.error(e); this.$message.error('系统错误，请联系开发者!'); }
    },
    // 拒绝订单
    rejectOrder(row) {
      this.$prompt('请输入拒绝原因', '拒绝订单', { confirmButtonText: '确定', cancelButtonText: '取消', inputPattern: /.+/, inputErrorMessage: '拒绝原因不能为空' })
        .then(({ value }) => {
          const reason = value || '';
          try {
            const tableName = 'acquisition_order';
            const primaryKey = 'Acquisition_Order_SerialNumber';
            const id = row && row[primaryKey];
            if (!id) { this.$message.error('未获取到订单编号'); return; }
            if (!this.fromPurchaseDetail) { this.$message.error('仅从采购订单入口可操作'); return; }

            httpRequest({ url: '/generalBusiness/generalQueryByTableNameWithOriginal', data: { Data: tableName, Condition: `${primaryKey}='${id}'` } })
              .then(data => {
                if (!Array.isArray(data) || data.length !== 1) { this.$message.error('订单不存在或存在重复记录'); return; }
                data[0].Row_Status = '3';
                const lJSONObject_Modify = {}; lJSONObject_Modify[tableName] = data;
                const lJSONObject_DataSet = {
                  Modify: lJSONObject_Modify,
                  Add: {
                    acquisition_order_examine_log: [{
                      Acquisition_Order_SerialNumber: id,
                      Reason: reason,
                      Operation_ID: getCookie('user') || ''
                    }],
                    base_operation_log: [{
                      Operation_Type: '0', Operation_Path: getRelativePath(), Operation_Description: '拒绝采购订单',
                      Operation_Main: JSON.stringify(deepClone(lJSONObject_Modify)),
                      Operation_Interface: 'generalSaveByRequestBody', Operation_IP: getIpAddress()
                    }]
                  }
                };
                return httpRequest({ contentType: 'JSON', url: '/generalBusiness/generalSaveByRequestBody', data: JSON.stringify({ Data: lJSONObject_DataSet }) });
              }).then(res => {
                if (res && (res.Status === 'success')) {
                  this.$message.success('已拒绝');
                  this.$set(row, 'Row_Status', '3');
                  // 刷新拒绝记录显示
                  this.fetchDetail();
                  // 成功后返回来源页
                  this.handleBack();
                }
                else if (res) { this.$message.error(res.Message || '保存失败'); }
              }).catch(() => this.$message.error('系统错误，请联系开发者!'));
          } catch (e) { console.error(e); this.$message.error('系统错误，请联系开发者!'); }
        }).catch(() => {});
    },
    formatRejectLog(log, idx) {
      const reason = (log && log.Reason) ? log.Reason : '';
      const time = (log && (log.Create_Date || log.Operation_Datetime)) ? `（${log.Create_Date || log.Operation_Datetime}）` : '';
      return `${idx + 1}. ${reason}${time}`;
    }
  }
});
